package com.eric.controller;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import com.eric.domain.dto.SysUserDto;
import com.eric.domain.po.SysUser;
import com.eric.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/loginInfo")
public class LoginInfoController {
    private final ISysUserService userService;


    //    查询已登录系统的用户Map
    @GetMapping("/getAllLoginId")
    public SaResult getAllLoginId(){
//        获取到已经登录系统的session数据
        List<String> sessions = StpUtil.searchSessionId("", 0, -1, false);
        ArrayList<Integer>ids = new ArrayList<>();
        for (String session : sessions) {
            int i = session.lastIndexOf(":")+1;
            String substring = session.substring(i);
            ids.add(Integer.parseInt(substring));
        }
        Map<Integer,String>loginUserMap = new HashMap<>();
        List<SysUser> sysUsers = userService.listByIds(ids);
        List<SysUserDto> sysUserDtos = BeanUtil.copyToList(sysUsers, SysUserDto.class);
        sysUserDtos.forEach(sysUserDto -> loginUserMap.put(sysUserDto.getId(),sysUserDto.getLoginName()));
        return SaResult.data(loginUserMap);
    }

    //   强制注销一个用户,强制注销等价于对方主动调用了注销方法，再次访问会提示：Token无效。
    @PostMapping("/forceLoginOut")
    @SaCheckRole(value = {"sys:coder","sys:superAdmin","sys:admin"},mode = SaMode.OR)
    public SaResult forceLoginOut(@RequestBody List<Integer>ids){
        if(ids.isEmpty()){
            return SaResult.error("id不能为空");
        }
        ids.forEach(StpUtil::logout);
        return SaResult.ok();
    }

    //    强制踢人下线,踢人下线不会清除Token信息，而是将其打上特定标记，再次访问会提示：Token已被踢下线。
    @PostMapping("/forceKickOut")
    @SaCheckRole(value = {"sys:coder","sys:superAdmin","sys:admin"},mode = SaMode.OR)
    public SaResult forceKickOut(@RequestBody List<Integer>ids){
        if(ids.isEmpty()){
            return SaResult.error("id不能为空");
        }
        ids.forEach(StpUtil::kickout);
        return SaResult.ok();
    }

    //    账号封禁
    @GetMapping("/loginDisable")
    @SaCheckRole(value = {"sys:coder","sys:superAdmin","sys:admin"},mode = SaMode.OR)
    public SaResult loginDisable(Integer hours,Integer id){
        if(hours == null||hours <= 0){
            hours = 1;
        }
        int seconds = hours * 3600;
        StpUtil.kickout(id);
        StpUtil.disable(id,seconds);
        return SaResult.ok();
    }

}
